package com.paiai.lslease.service.appuser;

import com.paiai.lslease.auto.dao.AppSysRoleDAO;
import com.paiai.lslease.auto.dao.AppSysUserDAO;
import com.paiai.lslease.auto.dao.AppSysUserRoleDAO;
import com.paiai.lslease.auto.model.*;
import com.paiai.lslease.dao.appuser.AppSysUserInfoDAO;
import com.paiai.lslease.model.AppLandlordAuthHouseInfo;
import com.paiai.lslease.service.landlordauth.AppLandlordAuthService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;

public class AppSysUserServiceImpl implements AppSysUserService {

    private static final Logger logger = LoggerFactory.getLogger(AppSysUserServiceImpl.class);
    private AppSysUserDAO appSysUserDAO;
    private AppSysRoleDAO appSysRoleDAO;
    private AppSysUserRoleDAO appSysUserRoleDAO;
    private AppSysUserInfoDAO appSysUserInfoDAO;
    @Autowired
    private AppLandlordAuthService appLandlordAuthService;

    public void setAppSysUserDAO(AppSysUserDAO appSysUserDAO) {
        this.appSysUserDAO = appSysUserDAO;
    }

    public void setAppSysRoleDAO(AppSysRoleDAO appSysRoleDAO) {
        this.appSysRoleDAO = appSysRoleDAO;
    }

    public void setAppSysUserRoleDAO(AppSysUserRoleDAO appSysUserRoleDAO) {
        this.appSysUserRoleDAO = appSysUserRoleDAO;
    }

    public void setAppSysUserInfoDAO(AppSysUserInfoDAO appSysUserInfoDAO) {
        this.appSysUserInfoDAO = appSysUserInfoDAO;
    }

    public int checkAppUserStateByWechatOpenId(String wechatOpenId) throws Exception {
        //根据微信OPENID验证用户状态 1 用户状态正常,请直接根据微信openid获取用户详情；-1 未注册，请引导用户绑定微信账号; 2 用户已标记为禁用；4 用户已标记为删除
        AppSysUserExample appSysUserExample = new AppSysUserExample();
        appSysUserExample.createCriteria().andWechatOpenIdEqualTo(wechatOpenId).andStateEqualTo(1);
        List<AppSysUser> appSysUserList = appSysUserDAO.selectByExample(appSysUserExample);
        if (appSysUserList == null || appSysUserList.size() == 0) {
            return -1;
        }
        return appSysUserList.get(0).getState();
    }

    public AppSysUser getAppSysUserInfoById(int userId) throws Exception {
        AppSysUser appSysUser = appSysUserDAO.selectByPrimaryKey(userId);
        if (!"1".equalsIgnoreCase(appSysUser.getState() + "")) {
            return null;
        }
        return appSysUser;
    }

    public AppSysUser getAppSysUserInfoByWechatOpenId(String wechatOpenId) throws Exception {
        AppSysUserExample appSysUserExample = new AppSysUserExample();
        appSysUserExample.createCriteria().andWechatOpenIdEqualTo(wechatOpenId).andStateEqualTo(1);
        List<AppSysUser> appSysUserList = appSysUserDAO.selectByExample(appSysUserExample);
        return appSysUserList == null || appSysUserList.size() == 0 ? null : appSysUserList.get(0);
    }

    public AppSysUser getAppSysUserInfoByMobile(String mobile) throws Exception {
        AppSysUserExample appSysUserExample = new AppSysUserExample();
        appSysUserExample.createCriteria().andMobileEqualTo(mobile).andStateEqualTo(1);
        List<AppSysUser> appSysUserList = appSysUserDAO.selectByExample(appSysUserExample);
        return appSysUserList == null || appSysUserList.size() == 0 ? null : appSysUserList.get(0);
    }

    @Override
    public boolean axaccountBinded(String mobile, String openId) throws Exception {
        AppSysUserExample appSysUserExample = new AppSysUserExample();
        appSysUserExample.createCriteria().andMobileEqualTo(mobile).andWechatOpenIdEqualTo(openId).andStateEqualTo(1);
        List<AppSysUser> appSysUserList = appSysUserDAO.selectByExample(appSysUserExample);
        return appSysUserList != null && appSysUserList.size() > 0;
    }

    public AppSysUser bindWXAccount(AppSysUser appSysUser) throws Exception {
        //根据微信账号查询用户是否绑定过
        AppSysUser appSysUser1 = getAppSysUserInfoByMobile(appSysUser.getWechatOpenId());
        if (appSysUser1 != null) {//根据微信账号查询用户，用户绑定过，准备更新用户手机号码
            appSysUser1.setUpdateTime(new Date());
            appSysUserDAO.updateByPrimaryKey(appSysUser1);
        } else {//没有绑定过，执行绑定
            //执行绑定
            appSysUserDAO.insert(appSysUser);//插入用户信息
            //插入用户与角色关联信息，新添加的用户默认是系统用户角色
            addSysRoleToUserById(appSysUserInfoDAO.selectNeweastAppSysUserId());
        }
        //查询用户是否有被授权的房源信息
        List<AppLandlordAuthHouseInfo> appLandlordAuthList = appLandlordAuthService.selectAppLandlordAuthListByUserMobile(appSysUser.getMobile());
        //有被授权的房源信息，为该用户增加房东授权管理员角色
        if (appLandlordAuthList != null && appLandlordAuthList.size() > 0 && !addLandlordAuthManagerRoleToUserByMobile(appSysUser.getMobile())) {
            logger.info("有被授权的房源信息，为该用户增加房东授权管理员角色失败");
            return null;
        }
        return getAppSysUserInfoByMobile(appSysUser.getMobile());
    }

    public boolean checkUserRegisterState(int userId) throws Exception {
        AppSysUserExample appSysUserExample = new AppSysUserExample();
        appSysUserExample.createCriteria().andIdEqualTo(userId).andStateEqualTo(1);
        List<AppSysUser> appSysUserList = appSysUserDAO.selectByExample(appSysUserExample);
        return appSysUserList != null && appSysUserList.size() != 0;
    }

    public int getSysUserRoleType() {
        return 1;
    }

    public int getTenantRoleType() {
        return 2;
    }

    public int getLandlordRoleType() {
        return 4;
    }

    public int getInstallWorkerRoleType() {
        return 16;
    }

    @Override
    public int getLanlordAuthManagerRoleType() {
        return 32;
    }

    public int getSysUserRoleId() throws Exception {
        AppSysRoleExample appSysRoleExample = new AppSysRoleExample();
        appSysRoleExample.createCriteria().andTypeEqualTo(getSysUserRoleType());
        return appSysRoleDAO.selectByExample(appSysRoleExample).get(0).getId();
    }

    public int getTenantRoleId() throws Exception {
        AppSysRoleExample appSysRoleExample = new AppSysRoleExample();
        appSysRoleExample.createCriteria().andTypeEqualTo(getTenantRoleType());
        return appSysRoleDAO.selectByExample(appSysRoleExample).get(0).getId();
    }

    public int getLandlordRoleId() throws Exception {
        AppSysRoleExample appSysRoleExample = new AppSysRoleExample();
        appSysRoleExample.createCriteria().andTypeEqualTo(getLandlordRoleType());
        return appSysRoleDAO.selectByExample(appSysRoleExample).get(0).getId();
    }

    public int getInstallWorkerRoleId() throws Exception {
        AppSysRoleExample appSysRoleExample = new AppSysRoleExample();
        appSysRoleExample.createCriteria().andTypeEqualTo(getInstallWorkerRoleType());
        return appSysRoleDAO.selectByExample(appSysRoleExample).get(0).getId();
    }

    public int getLanlordAuthManagerRoleId() throws Exception {
        AppSysRoleExample appSysRoleExample = new AppSysRoleExample();
        appSysRoleExample.createCriteria().andTypeEqualTo(getLanlordAuthManagerRoleType());
        return appSysRoleDAO.selectByExample(appSysRoleExample).get(0).getId();
    }

    public boolean userExist(int userId) throws Exception {
        return getAppSysUserInfoById(userId) != null;
    }

    public boolean userBelongRoleIdByUserId(int userId, int roleId) throws Exception {
        List<AppSysUserRole> appSysUserRoleList = selectSysUserRoleList(userId);
        if (appSysUserRoleList == null || appSysUserRoleList.size() == 0) {
            return false;
        }
        for (AppSysUserRole appSysUserRole : appSysUserRoleList) {
            if (roleId == appSysUserRole.getRoleId()) {
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean userBelongRoleIdByUserMobile(String userMobile, int roleId) throws Exception {
        AppSysUser appSysUser = getAppSysUserInfoByMobile(userMobile);
        return appSysUser != null && userBelongRoleIdByUserId(appSysUser.getId(), roleId);
    }

    public boolean userBelongTenant(int userId) throws Exception {
        return userBelongRoleIdByUserId(userId, getTenantRoleId());
    }

    public boolean userBelongLandlord(int userId) throws Exception {
        return userBelongRoleIdByUserId(userId, getLandlordRoleId());
    }

    public boolean userBelongInstallWorker(int userId) throws Exception {
        return userBelongRoleIdByUserId(userId, getInstallWorkerRoleId());
    }

    @Override
    public boolean userBelongLandlordAuthManagerByUserMobile(String userMobile) throws Exception {
        return userBelongRoleIdByUserMobile(userMobile, getLanlordAuthManagerRoleId());
    }

    @Override
    public boolean userBelongLandlordAuthManagerById(int userId) throws Exception {
        return userBelongRoleIdByUserId(userId, getLanlordAuthManagerRoleId());
    }

    @Override
    public List<AppSysUserRole> selectSysUserRoleList(int userId) throws Exception {
        AppSysUserRoleExample appSysUserRoleExample = new AppSysUserRoleExample();
        appSysUserRoleExample.createCriteria().andUserIdEqualTo(userId).andItem1EqualTo("1");
        return appSysUserRoleDAO.selectByExample(appSysUserRoleExample);
    }

    @Override
    public boolean checkRoleIdExist(int roleId) throws Exception {
        return appSysRoleDAO.selectByPrimaryKey(roleId) != null;
    }

    @Override
    public boolean checkUserRoleExist(int userId, int roleId) throws Exception {
        AppSysUserRoleExample appSysUserRoleExample = new AppSysUserRoleExample();
        appSysUserRoleExample.createCriteria().andUserIdEqualTo(userId).andRoleIdEqualTo(roleId).andItem1EqualTo("1");
        return appSysUserRoleDAO.selectByExample(appSysUserRoleExample).size() > 0;
    }

    @Override
    public boolean addRoleToUserByUserId(int userId, int roleId) throws Exception {
        if (!checkUserRegisterState(userId)) {
            return false;
        }
        if (!checkRoleIdExist(roleId)) {
            return false;
        }
        if (checkUserRoleExist(userId, roleId)) {//已经有这个角色了，不再重新添加
            return true;
        }
        //没有这个角色，添加这个角色
        AppSysUserRole appSysUserRole = new AppSysUserRole();
        appSysUserRole.setUserId(userId);
        appSysUserRole.setRoleId(roleId);
        appSysUserRole.setItem1("1");
        appSysUserRole.setInsertTime(new Date());
        appSysUserRole.setUpdateTime(new Date());
        appSysUserRoleDAO.insert(appSysUserRole);
        return true;
    }

    @Override
    public boolean addRoleToUserByUserMobile(String userMobile, int roleId) throws Exception {
        AppSysUser appSysUser = getAppSysUserInfoByMobile(userMobile);
        return appSysUser != null && addRoleToUserByUserId(appSysUser.getId(), roleId);
    }

    @Override
    public boolean deleteRoleToUserByUserId(int userId, int roleId) throws Exception {
        if (!checkUserRegisterState(userId)) {
            return false;
        }
        if (!checkRoleIdExist(roleId)) {
            return false;
        }
        if (!checkUserRoleExist(userId, roleId)) {//不存在这个角色，不需要删除
            return true;
        }
        AppSysUserRoleExample appSysUserRoleExample = new AppSysUserRoleExample();
        appSysUserRoleExample.createCriteria().andUserIdEqualTo(userId).andRoleIdEqualTo(roleId).andItem1EqualTo("1");
        AppSysUserRole appSysUserRole = new AppSysUserRole();
        appSysUserRole.setItem1("-1");
        appSysUserRole.setUpdateTime(new Date());
        return appSysUserRoleDAO.updateByExampleSelective(appSysUserRole, appSysUserRoleExample) > 0;
    }

    @Override
    public boolean deleteRoleToUserByUserMobile(String userMobile, int roleId) throws Exception {
        AppSysUser appSysUser = getAppSysUserInfoByMobile(userMobile);
        return appSysUser != null && deleteRoleToUserByUserId(appSysUser.getId(), roleId);
    }

    @Override
    public boolean addSysRoleToUserById(int userId) throws Exception {
        return addRoleToUserByUserId(userId, getSysUserRoleId());
    }

    @Override
    public boolean deleteSysRoleToUserById(int userId) throws Exception {
        return deleteRoleToUserByUserId(userId, getSysUserRoleId());
    }

    public boolean addTenantRoleToUserById(int userId) throws Exception {
        return addRoleToUserByUserId(userId, getTenantRoleId());
    }

    public boolean addTenantRoleToUserByMobile(String userMobile) throws Exception {
        return addRoleToUserByUserMobile(userMobile, getTenantRoleId());
    }

    public boolean deleteTenantRoleToUser(int userId) throws Exception {
        return deleteRoleToUserByUserId(userId, getTenantRoleId());
    }

    @Override
    public boolean addLandlordRoleToUserById(int userId) throws Exception {
        return addRoleToUserByUserId(userId, getLandlordRoleId());
    }

    @Override
    public boolean deleteLandlordRoleToUserById(int userId) throws Exception {
        return deleteRoleToUserByUserId(userId, getLandlordRoleId());
    }

    @Override
    public boolean addInstallWorkerRoleToUserById(int userId) throws Exception {
        return addRoleToUserByUserId(userId, getInstallWorkerRoleId());
    }

    @Override
    public boolean deleteInstallWorkerRoleToUserById(int userId) throws Exception {
        return deleteRoleToUserByUserId(userId, getInstallWorkerRoleId());
    }

    @Override
    public boolean addLandlordAuthManagerRoleToUserByMobile(String userMobile) throws Exception {
        return addRoleToUserByUserMobile(userMobile, getLanlordAuthManagerRoleId());
    }

    @Override
    public boolean deleteLandlordAuthManagerRoleToUserById(int userId) throws Exception {
        return deleteRoleToUserByUserId(userId, getLanlordAuthManagerRoleId());
    }

    @Override
    public boolean deleteLandlordAuthManagerRoleToUserByMobile(String userMobile) throws Exception {
        return deleteRoleToUserByUserMobile(userMobile, getLanlordAuthManagerRoleId());
    }

    @Override
    public AppSysUser modifyUserInfoByPrimaryKey(AppSysUser appSysUser) throws Exception {
        appSysUserDAO.updateByPrimaryKey(appSysUser);
        return getAppSysUserInfoById(appSysUser.getId());
    }

}
